package com.smartthinking.CICPNL.home.activity;

import java.util.ArrayList;
import java.util.Dictionary;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.R.id;
import com.smartthinking.CICPNL.home.objects.App_ImageLoader;

public class Ponentes extends Activity {
        public ListView list;
        public ListAdapter adapter;
        public Dialog progressDialog;
        public App_ImageLoader imageLoader;
        public static ArrayList<Dictionary<String,String>> TraeDatos = null;
        public static ArrayList<Dictionary<String,String>> Splash = null;
        private Intent intent;

        protected String QRY_BUSCADOR;
        public Integer EVEIDR;
        public TextView txtbusqueda;
        String busqueda = "";
        private boolean favoritos = false;
        Utilities util;
        private String strPonencia;
        boolean inicial;

        public void voidFinish(View V) {
        	finish();
        }

        public void abrirMenuLateral(View V) {
                intent = new Intent(Ponentes.this, MenuLateral.class);
                startActivity(intent);
        }

        @Override
        public void onBackPressed() {
        }
        
        public void onConfigurationChanged(Configuration newConfig) {
                super.onConfigurationChanged(newConfig);
        }
        
        @Override
        public void onCreate(Bundle savedInstanceState) {
        	super.onCreate(savedInstanceState);
    		requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.ui_listview);

            util = new Utilities();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            TextView Titulo = (TextView) this.findViewById(id.tv_listView_Titulo);
            Titulo.setText(getResources().getString(R.string.modulo_ponentes));
                
    		Intent intent = getIntent();
    	    strPonencia = intent.getStringExtra("PONENCIA");
    	    if(strPonencia == null){
    	    	strPonencia = "";
    	    }
    	    if(strPonencia.equals("null")){
    	    	strPonencia = "";
    	    }
            
        	EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
        	txtbusc.setOnEditorActionListener(new OnEditorActionListener() {
        		@Override
        		public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
        			if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
	        		    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	        		    in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
	        			buscar();
	        			return true;
        			}
        			return false;
        		}
        	});
        	EVEIDR = Utilities.EVE_IDR;            
            txtbusqueda = (TextView) this.findViewById(id.et_buscar_buscar);
            CargarContenido();
        }
       
    	public void borrar(View v){
    		EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
    		txtbusc.setText("");
    		buscar();
    	}
       
        private void CargarContenido() {
                new AsyncContenido().execute("");
        }
       
        private class AsyncContenido extends AsyncTask<String, String, String>{
               
        	@Override
            protected void onPreExecute() {
        		super.onPreExecute();
        		progressDialog = ProgressDialog.show(Ponentes.this, "",getResources().getString(R.string.msg_cargando));
        	}

        	protected String doInBackground(String... params) {
    		    String strFavoritos = "";
    		    if (favoritos) {
    		        strFavoritos = util.getFavoritos(Ponentes.this,"PONENTE");
    		        if (strFavoritos.length()>0) {
    		            strFavoritos = "and pon_idr in("+strFavoritos+")";
    		        }else{
    		            strFavoritos = "and pon_idr in(9999999)";
    		        }
    		    }
    		    
    		    String strqry =  "";
    		    Log.d(null,busqueda);
    		    if(strPonencia.length()<=0){
        		    if (busqueda.length()<=0) {
        		    	strqry = "select pon_idr,pon_nombre,pon_paterno,pon_materno,pon_foto from ponentes where eve_idr = "+EVEIDR+" "+strFavoritos+" order by pon_nombre";
        		    }else{
                		strqry = "select pon_idr,pon_nombre,pon_paterno,pon_materno,pon_foto " +
                				"from ponentes " +
                                "where eve_idr=" + EVEIDR +
                                " and upper(pon_nombre || ' ' || pon_paterno  || ' ' || pon_materno) like upper('%" + busqueda + "%') or " +
                                " upper(pon_puesto) like upper('%" + busqueda + "%') or " +
                                " upper(pon_perfil) like upper('%" + busqueda + "%') or " + 
                                " upper(pon_perfil_en) like upper('%" + busqueda + "%') or " +
                                " upper(pon_empresa) like upper('%" + busqueda + "%') " + strFavoritos + " " +
                                " order by pon_nombre";
        		    }    		    	
    		    }else{
        		    if (busqueda.length()<=0) {
        		    	strqry = "select a.pon_idr,a.pon_nombre,a.pon_paterno,a.pon_materno,a.pon_foto from ponentes a inner join ponentes_ponencias b on a.pon_idr = b.pon_idr where b.nen_idr = "+strPonencia+" and a.eve_idr = "+EVEIDR+" "+strFavoritos+" order by pon_nombre";
        		    }else{
                		strqry = "select a.pon_idr,a.pon_nombre,a.pon_paterno,a.pon_materno,a.pon_foto " +
                				" from ponentes a inner join ponentes_ponencias b on a.pon_idr = b.pon_idr " +
                                " where b.nen_idr = "+strPonencia+" and a.eve_idr=" + EVEIDR +
                                " and upper(pon_nombre || ' ' || pon_paterno  || ' ' || pon_materno) like upper('%" + busqueda + "%') or " +
                                " upper(pon_puesto) like upper('%" + busqueda + "%') or " +
                                " upper(pon_perfil) like upper('%" + busqueda + "%') or " + 
                                " upper(pon_perfil_en) like upper('%" + busqueda + "%') or " +
                                " upper(pon_empresa) like upper('%" + busqueda + "%') " + strFavoritos + " " +
                                " order by pon_nombre";
        		    }
    		    }

        		TraeDatos = Utilities.qry2(getApplicationContext(), strqry);
        		
    			//BANNERS Y SPLASH
    			if(inicial){
    				String qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH PONENTES' ORDER BY b.ban_nombre";
    				Splash = Utilities.qry2(getApplicationContext(), qry);
    			}
        		
                return null;
        	}
        	
        	protected void onPostExecute(String result) {
        		super.onPostExecute(result);
       
        		Resources res = getResources();
                ListView listView = (ListView) findViewById(id.list);
                PonentesArrayAdapter adapter = new PonentesArrayAdapter(Ponentes.this, TraeDatos, res.getString(R.string.QRY_SERVLET));
                listView.setAdapter(adapter);
                               
                listView.setOnItemClickListener(new OnItemClickListener() {
                	@Override
                	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                		muestra_detalle(TraeDatos.get(position).get("pon_idr").toString());
                	}
                });
                progressDialog.dismiss();
                
    		    //presento splash
    		    if(inicial){
    		    	inicial = false;
    		    	Dictionary<String, String> dic = null;
    		    	if(Splash.size()>0){
    			    	dic = Splash.get(0);
    			    	String strPoster = dic.get("ban_url").toString();
    				    String strTimer = dic.get("ban_timer").toString();
    				    String strPatrocinador = dic.get("pat_idr").toString();
    				    if (strPoster.equals("null")) {
    				        strPoster = "";
    				    }
    				    if(strPoster.length()>0){
    						intent = new Intent(Ponentes.this, Splash2.class);
    						Bundle bund = new Bundle();
    						bund.putString("PUT_IMG",strPoster);
    						bund.putString("PUT_PAT",strPatrocinador);
    						bund.putString("PUT_TIME",strTimer);
    						intent.putExtras(bund);
    						startActivity(intent);
    				    }
    			    }
    		    }
        	}
        }

        private void muestra_detalle(String idpon){
        	intent = new Intent(this, PonentesDetalle.class);
            Bundle bund = new Bundle();
            bund.putString("idponente",idpon);
            intent.putExtras(bund);
            startActivity(intent);
        }
       
        public class Hoteles_Adapter extends BaseAdapter {

        	private LayoutInflater inflater = null;
            private ArrayList<Dictionary> data;
            public Hoteles_Adapter(ArrayList<Dictionary> d) {

                        data = d;
                        inflater = (LayoutInflater) Ponentes.this
                                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                        imageLoader = new App_ImageLoader(
                                        Ponentes.this.getApplicationContext());

                }

                public int getCount() {
                        return data.size();
                }

                public Object getItem(int position) {
                        return position;
                }

                public long getItemId(int position) {
                        return position;
                }

                public class ViewHolder {

                        public TextView tvTitulo;
                        public ImageView images;

                }

                public View getView(int position, View convertView, ViewGroup parent) {

                        View vi = convertView;
                        ViewHolder holder;

                        if (convertView == null) {

                                vi = inflater.inflate(R.layout.ui_ponentes_items, null);

                                holder = new ViewHolder();

                                holder.tvTitulo = (TextView) vi
                                                .findViewById(R.id.tv_ponenetesitems_ponent);

                                holder.images = (ImageView) vi
                                                .findViewById(R.id.iv_ponenetesitems_imagen);

                                vi.setTag(holder);

                        } else

                                holder = (ViewHolder) vi.getTag();

                        String Titulo = data.get(position).get("pon_nombre").toString()
                                        + " " + data.get(position).get("pon_paterno").toString()
                                        + " " + data.get(position).get("pon_materno").toString();

                        holder.tvTitulo.setText(Titulo);

                        String url_img = getString(R.string.QRY_URL_IMG)
                                        + data.get(position).get("pon_foto").toString()
                                                        .replace(" ", "%20");

                        holder.images.setTag(url_img);

                        try {

                                imageLoader.DisplayImage(url_img, Ponentes.this, holder.images);

                        } catch (Exception ex) {

                                String s = ex.getMessage().toString();

                        }

                        return vi;

                }
        }
       
        public void fFavoritos(View v){
    		Button btnf = (Button) findViewById(R.id.iv_btn_favoritos);
    		Button btnt = (Button) findViewById(R.id.iv_btn_todos);
    		if (favoritos){
    			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_des);
    			btnt.setBackgroundResource(R.drawable.lst_btn_todos_act);
    			favoritos = false;
    		}else{
    			btnf.setBackgroundResource(R.drawable.lst_btn_favoritos_act);	
    			btnt.setBackgroundResource(R.drawable.lst_btn_todos_des);
    			favoritos = true;
    		}
    		CargarContenido();
        }
       
        public void detalle(View v){
                intent = new Intent(this, PonentesDetalle.class);
                startActivity(intent);
        }
       
        public void voidbusqueda(View v){
        	InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            buscar();
        }
        
    	public void buscar(){
    		String strBusqueda = ((EditText) findViewById(id.et_buscar_buscar)).getText().toString().trim();
    		if(!strBusqueda.equals(busqueda)){
    			busqueda = strBusqueda;
    			CargarContenido();
    		}
    	}
       
}
